from machine import I2S, Pin

"""
MAX98357功放
"""
class Max98357:
    def __init__(self, sck_pin, ws_pin, sd_pin, i2s_num = 0):
        self.__sck = sck_pin
        self.__ws = ws_pin
        self.__sd = sd_pin
        self.__i2s = i2s_num
        self.__audio = None

        self.init()

    def init(self):
        """
            sd -- DIN
            sck --- BCLK
            ws -- LRC
            GND -- GND
            5V或3.3V -- VCC
            """
        if self.__audio:
            return

        try:
            self.__audio = I2S(
                self.__i2s,
                sck=Pin(self.__sck),
                ws=Pin(self.__ws),
                sd=Pin(self.__sd),
                mode=I2S.TX,
                bits=16,
                format=I2S.MONO,
                rate=8000,
                ibuf=20000,
            )
            print(f"MAX98357初始化成功: I2S{i2s_num}")
        except Exception as e:
            print(f"MAX98357初始化失败: {e}")
            self.__audio = None

    def play_bytes(self, audio_bytes):
        if not self.__audio:
            print("音频设备未初始化")
            return
            
        try:
            data_view = memoryview(audio_bytes)
            while True:
                play_data = data_view[0:1024]
                data_view = data_view[1024:]
                num_read = len(play_data)

                if num_read == 0:
                    break

                num_written = 0
                while num_written < num_read:
                    num_written += self.__audio.write(play_data[num_written:num_read])
        except Exception as e:
            print("播放错误:", e)

    def stop(self):
        """停止播放并销毁I2S实例"""
        if self.__audio:
            self.__audio.deinit()
            self.__audio = None